package service

import (
	"context"

	"gitee.com/zhaokangming/tiny-ticktok/dao"
	"gitee.com/zhaokangming/tiny-ticktok/model"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/app"
)

type VideoListResponse struct {
	app.Response
	VideoList []model.Video `json:"video_list"`
}

func Favorite(ctx context.Context, uid, vid int64) error {
	return dao.CreateFavorite(ctx, uid, vid)
}

func CancelFavorite(ctx context.Context, uid, vid int64) error {
	return dao.DeleteFavorite(ctx, uid, vid)
}

func GetFavoriteList(ctx context.Context, uid, targetID int64) (*VideoListResponse, error) {
	vids, err := dao.MGetFavoriteVideoIDs(ctx, targetID)
	if err != nil {
		return nil, err
	}

	res := new(VideoListResponse)
	res.VideoList = make([]model.Video, len(vids))
	videos, err := dao.MGetVideosByIDs(ctx, vids)
	if err != nil {
		return res, err
	}

	for i, v := range videos {
		user, err := QueryUser(ctx, uid, v.AuthorID)
		if err != nil {
			return nil, err
		}

		res.VideoList[i].Author = *user
		res.VideoList[i].Id = int64(v.ID)
		res.VideoList[i].FavoriteCount = dao.QueryFavoriteCount(ctx, int64(v.ID))
		res.VideoList[i].CommentCount, err = dao.QueryCommentCount(ctx, int64(v.ID))
		if err != nil {
			return res, err
		}

		res.VideoList[i].IsFavorite = dao.QueryIsFavorite(ctx, user.Id, int64(v.ID))
		res.VideoList[i].CoverUrl = v.CoverUrl
		res.VideoList[i].PlayUrl = v.PlayUrl
	}

	return res, nil
}
